package com.halfsword.creativecraft.datagen;

import com.halfsword.creativecraft.CreativeCraft;
import com.halfsword.creativecraft.block.BlockLoader;
import com.halfsword.creativecraft.item.ItemLoader;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import net.minecraft.world.item.ArmorItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.armortrim.TrimMaterial;
import net.minecraft.world.item.armortrim.TrimMaterials;
import net.minecraft.world.level.block.Block;
import net.minecraftforge.client.model.generators.ItemModelBuilder;
import net.minecraftforge.client.model.generators.ItemModelProvider;
import net.minecraftforge.client.model.generators.ModelFile;
import net.minecraftforge.common.data.ExistingFileHelper;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;

import java.util.LinkedHashMap;

public class SpaceItemModelProvider extends ItemModelProvider {
    public SpaceItemModelProvider(PackOutput output, ExistingFileHelper existingFileHelper) {
        super(output, CreativeCraft.MOD_ID, existingFileHelper);
    }

    // 盔甲装饰材质及其对应的数值
    private static final LinkedHashMap<ResourceKey<TrimMaterial>, Float> TRIM_MATERIALS = new LinkedHashMap<>();
    static {
        // 初始化所有原版装饰材质及其权重值
        TRIM_MATERIALS.put(TrimMaterials.QUARTZ, 0.1F);
        TRIM_MATERIALS.put(TrimMaterials.IRON, 0.2F);
        TRIM_MATERIALS.put(TrimMaterials.NETHERITE, 0.3F);
        TRIM_MATERIALS.put(TrimMaterials.REDSTONE, 0.4F);
        TRIM_MATERIALS.put(TrimMaterials.COPPER, 0.5F);
        TRIM_MATERIALS.put(TrimMaterials.GOLD, 0.6F);
        TRIM_MATERIALS.put(TrimMaterials.EMERALD, 0.7F);
        TRIM_MATERIALS.put(TrimMaterials.DIAMOND, 0.8F);
        TRIM_MATERIALS.put(TrimMaterials.LAPIS, 0.9F);
        TRIM_MATERIALS.put(TrimMaterials.AMETHYST, 1.0F);
    }

    // 为盔甲物品生成修剪变体
    private void trimmedArmorItem(RegistryObject<Item> itemRegistryObject) {
        final String MOD_ID = CreativeCraft.MOD_ID;

        if (itemRegistryObject.get() instanceof ArmorItem armorItem) {
            // 遍历所有装饰材质
            TRIM_MATERIALS.entrySet().forEach(entry -> {
                ResourceKey<TrimMaterial> trimMaterial = entry.getKey();
                float trimValue = entry.getValue();

                // 根据盔甲类型获取对应的字符串标识
                String armorType = switch (armorItem.getEquipmentSlot()) {
                    case HEAD -> "helmet";
                    case CHEST -> "chestplate";
                    case LEGS -> "leggings";
                    case FEET -> "boots";
                    default -> "";
                };

                // 获取基础盔甲物品的路径（去掉命名空间）
                String armorItemPath = ForgeRegistries.ITEMS.getKey(armorItem).getPath();

                // 创建装饰材质路径（使用新的ResourceLocation API）
                String trimPath = "trims/items/%s_trim_%s".formatted(
                        armorType,
                        trimMaterial.location().getPath()
                );

                // 创建修剪变体的唯一名称
                String currentTrimName = "%s_%s_trim".formatted(
                        armorItemPath,
                        trimMaterial.location().getPath()
                );

                // 使用新的API创建资源定位符
                ResourceLocation armorItemResLoc = ResourceLocation.fromNamespaceAndPath(MOD_ID, "item/" + armorItemPath);
                ResourceLocation trimResLoc = ResourceLocation.fromNamespaceAndPath("minecraft", trimPath);
                ResourceLocation trimNameResLoc = ResourceLocation.fromNamespaceAndPath(MOD_ID, currentTrimName);

                // 确保纹理文件存在（避免验证错误）
                existingFileHelper.trackGenerated(trimResLoc, PackType.CLIENT_RESOURCES, ".png", "textures");

                // 生成修剪变体模型
                getBuilder(currentTrimName)
                        .parent(new ModelFile.UncheckedModelFile("item/generated"))
                        .texture("layer0", armorItemResLoc)  // 基础盔甲纹理
                        .texture("layer1", trimResLoc);      // 装饰材质纹理

                // 为原始盔甲添加修剪覆盖
                this.withExistingParent(armorItemPath, mcLoc("item/generated"))
                        .override()
                        .model(new ModelFile.UncheckedModelFile(trimNameResLoc))
                        .predicate(mcLoc("trim_type"), trimValue)
                        .end()
                        .texture("layer0", armorItemResLoc);
            });
        }
    }

    @Override
    protected void registerModels() {
        // 注册简单物品模型
        simpleItem(ItemLoader.GEMSPACE);
        simpleItem(ItemLoader.RAWSPACE);
        simpleItem(ItemLoader.FUELSPACE);
        simpleItem(ItemLoader.INGOT_TITANIUM);
        simpleItem(ItemLoader.LINKAGE_I);
        simpleItem(ItemLoader.SMALL_GEAR_IRON);
        simpleItem(ItemLoader.PISTON_I);
        simpleItem(ItemLoader.CYLINDER_I);
        simpleItem(ItemLoader.AXIS_I);
        simpleItem(ItemLoader.SPACEDECECTOR);
        simpleItem(ItemLoader.CORNFIELD_CHASE_DISC);
        simpleItem(ItemLoader.BLUEBERRY);
        simpleItem(ItemLoader.BLUEBERRY_SEEDS);
        simpleItem(ItemLoader.SORGHUM);
        simpleItem(ItemLoader.SORGHUM_SEEDS);
        simpleBlockItemTexture(BlockLoader.CALENDULA);
        //异常收录
        withExistingParent(ItemLoader.NOTHING_SPAWN_EGG.getId().getPath(),mcLoc("item/template_spawn_egg"));

        // 注册手持物品模型
        handheldItem(ItemLoader.SWORDSPACE);
        handheldItem(ItemLoader.SHOVELSPACE);
        handheldItem(ItemLoader.PICKAXESPACE);
        handheldItem(ItemLoader.HOESPACE);
        handheldItem(ItemLoader.AXESPACE);

        // 注册空间系列盔甲
        trimmedArmorItem(ItemLoader.HELMETSPACE);
        trimmedArmorItem(ItemLoader.CHESTPLATESPACE);
        trimmedArmorItem(ItemLoader.LEGGINGSSPACE);
        trimmedArmorItem(ItemLoader.BOOTSSPACE);

        // 注册末影系列盔甲
        trimmedArmorItem(ItemLoader.HELMETENDER);
        trimmedArmorItem(ItemLoader.CHESTPLATEENDER);
        trimmedArmorItem(ItemLoader.LEGGINGSENDER);
        trimmedArmorItem(ItemLoader.BOOTSENDER);

        // 注册方块物品模型
        simpleBlockItem(BlockLoader.DOOR_SPACE);
        fenceItem(BlockLoader.FENCE_SPACE, BlockLoader.BLOCK_SPACE);
        buttonItem(BlockLoader.BUTTON_SPACE, BlockLoader.BLOCK_SPACE);
        wallItem(BlockLoader.WALL_SPACE, BlockLoader.BLOCK_SPACE);
        evenSimplerBlockItem(BlockLoader.STAIRS_SPACE);
        evenSimplerBlockItem(BlockLoader.SLAB_SPACE);
        evenSimplerBlockItem(BlockLoader.PRESSURE_PLATE_SPACE);
        evenSimplerBlockItem(BlockLoader.FENCE_GATE_SPACE);
        trapdoorItem(BlockLoader.TRAPDOOR_SPACE);
    }

    // 创建简单物品模型
    private ItemModelBuilder simpleItem(RegistryObject<Item> item) {
        String path = item.getId().getPath();
        return withExistingParent(path, mcLoc("item/generated"))
                .texture("layer0", modLoc("item/" + path));
    }


    // 创建简单方块物品模型
    private ItemModelBuilder simpleBlockItem(RegistryObject<Block> block) {
        String path = block.getId().getPath();
        return withExistingParent(path, mcLoc("item/generated"))
                .texture("layer0", modLoc("item/" + path));
    }

    private ItemModelBuilder simpleBlockItemTexture(RegistryObject<Block> block) {
        String path = block.getId().getPath();
        return withExistingParent(path, mcLoc("item/generated"))
                .texture("layer0", modLoc("block/" + path));
    }

    // 创建基于方块的简单物品模型
    public void evenSimplerBlockItem(RegistryObject<Block> block) {
        String path = ForgeRegistries.BLOCKS.getKey(block.get()).getPath();
        withExistingParent(path, modLoc("block/" + path));
    }

    // 创建活板门物品模型
    public void trapdoorItem(RegistryObject<Block> block) {
        String path = ForgeRegistries.BLOCKS.getKey(block.get()).getPath();
        withExistingParent(path, modLoc("block/" + path + "_bottom"));
    }

    // 创建栅栏物品模型
    public void fenceItem(RegistryObject<Block> block, RegistryObject<Block> baseBlock) {
        String path = ForgeRegistries.BLOCKS.getKey(block.get()).getPath();
        String basePath = ForgeRegistries.BLOCKS.getKey(baseBlock.get()).getPath();

        withExistingParent(path, mcLoc("block/fence_inventory"))
                .texture("texture", modLoc("block/" + basePath));
    }

    // 创建按钮物品模型
    public void buttonItem(RegistryObject<Block> block, RegistryObject<Block> baseBlock) {
        String path = ForgeRegistries.BLOCKS.getKey(block.get()).getPath();
        String basePath = ForgeRegistries.BLOCKS.getKey(baseBlock.get()).getPath();

        withExistingParent(path, mcLoc("block/button_inventory"))
                .texture("texture", modLoc("block/" + basePath));
    }

    // 创建墙物品模型
    public void wallItem(RegistryObject<Block> block, RegistryObject<Block> baseBlock) {
        String path = ForgeRegistries.BLOCKS.getKey(block.get()).getPath();
        String basePath = ForgeRegistries.BLOCKS.getKey(baseBlock.get()).getPath();

        withExistingParent(path, mcLoc("block/wall_inventory"))
                .texture("wall", modLoc("block/" + basePath));
    }

    // 创建手持物品模型
    private ItemModelBuilder handheldItem(RegistryObject<Item> item) {
        String path = item.getId().getPath();
        return withExistingParent(path, mcLoc("item/handheld"))
                .texture("layer0", modLoc("item/" + path));
    }
}
